package com.parking.order.consumer;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.parking.common.core.model.StateData;
import com.parking.order.dao.OrderInfoDao;
import com.parking.order.dao.OrderOvertimeDao;
import com.parking.order.model.OrderInfo;
import com.parking.order.model.OrderOvertime;
import com.parking.order.state.CommonOrderStateChange;
import com.parking.order.util.AlipayUtil;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * 订单支付Consumer类
 * */
@Component
public class PayConsumer {
    /**
     * 支付宝工具类
     * */
    @Autowired
    private AlipayUtil alipayUtil;
    /**
     * 消息队列工具类
     * */
    @Autowired
    private RabbitTemplate rabbitTemplate;
    /**
     * 订单信息数据层
     * */
    @Autowired
    private OrderInfoDao orderInfoDao;
    /**
     * 订单状态改变工具类
     * */
    @Autowired
    private CommonOrderStateChange commonOrderStateChange;

    /**
     * 超时订单数据层
     * */
    @Autowired
    private OrderOvertimeDao orderOvertimeDao;
    /**
     * 订单支付Consumer
     * */
    @RabbitHandler
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value="dead"),
                    exchange = @Exchange(value="delay",type="direct"),
                    key="order2"
            )
    })
    public void confirmOrderState(String orderInfoNum) throws Exception {
        System.out.println("===============消息队列检测 检测订单编号:"+orderInfoNum+"===============");
        String payState = alipayUtil.selectOrderPayState(orderInfoNum);
        JSONObject jsonObject = JSONUtil.parseObj(JSONUtil.parseObj(payState).getStr("alipay_trade_query_response"));
        String trade_status = jsonObject.getStr("trade_status");
        LocalDateTime now = LocalDateTime.now();
        if ("TRADE_SUCCESS".equals(trade_status)) {
            String payTimeStr = jsonObject.getStr("send_pay_date");
            DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime payTime = LocalDateTime.parse(payTimeStr,pattern);

            if(orderInfoNum.length()== StateData.ORDER_NUM_OVERTIME_LENGTH_SNOWFLAKE){
                orderInfoNum = StateData.fromOvertimeNumToOrder(orderInfoNum);
                // 超时订单支付
                OrderOvertime overtime = orderOvertimeDao.selectOne(new QueryWrapper<OrderOvertime>().eq("order_info_num",orderInfoNum));
                if(Objects.equals(overtime.getPayState(), StateData.ORDER_OVERTIME_NOT_PAY)){
                    System.out.println("===============检测结果:超时订单支付=======================");
                    orderInfoDao.update(null,new UpdateWrapper<OrderInfo>().eq("order_info_num",orderInfoNum).set("order_info_state",StateData.ORDER_STATE_END).set("is_overtime",StateData.ORDER_IS_OVERTIME_FINISH).set("order_update_time",now));

                    overtime.setPayState(StateData.ORDER_OVERTIME_PAID);
                    overtime.setPayTime(payTime);
                    overtime.setUpdateTime(LocalDateTime.now());
                    orderOvertimeDao.updateById(overtime);

                    rabbitTemplate.convertAndSend("orderLog",orderInfoNum+",用户支付超时订单 消息队列查询支付状态延迟确认,"+StateData.ORDER_LOG_PERSON_TYPE_SYSTEM+",系统自动");

                    rabbitTemplate.convertAndSend("moneyOvertime",orderInfoNum);
                }
            }
            if(orderInfoNum.length()==StateData.ORDER_NUM_LENGTH_SNOWFLAKE){
                // 普通订单支付
                OrderInfo order = orderInfoDao.selectOne(new QueryWrapper<OrderInfo>().eq("order_info_num",orderInfoNum));
                if(Objects.equals(order.getOrderInfoState(), StateData.ORDER_STATE_NO_PAID)){
                    System.out.println("===============检测结果:普通订单支付=======================");
                    Integer type = StateData.ORDER_STATE_NOPAY_TO_SHBEGIN_RABBITMQ;
                    System.out.println("当前时间:"+now);
                    System.out.println("支付时间:"+payTime);
                    if(now.isBefore(order.getStartTime())) {
                        System.out.println("===============现在订单还未开始 进入已支付状态=======================");
                        commonOrderStateChange.stateChangeNopayToPaid(orderInfoNum,type,payTime);
                    }
                    else {
                        System.out.println("===============现在订单已经开始 进入可开始状态=======================");
                        commonOrderStateChange.stateChangeNopayToShbegin(orderInfoNum,type,payTime);
                    }
                }
            }
        } else {
            if(orderInfoNum.length()==StateData.ORDER_NUM_LENGTH_SNOWFLAKE){
                // 普通订单未支付
                OrderInfo order = orderInfoDao.selectOne(new QueryWrapper<OrderInfo>().eq("order_info_num",orderInfoNum));
                if(Objects.equals(order.getOrderInfoState(), StateData.ORDER_STATE_NO_PAID)){
                    System.out.println("===============检测结果:普通订单未支付=======================");
                    Integer type = StateData.ORDER_STATE_NOPAY_TO_PAID_RABBITMQ;
                    commonOrderStateChange.stateChangeNopayToCancel(orderInfoNum,type);
                }
            }
        }
    }
}
